<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
let chart = null

const creditLevels = [
  { name: 'A级', value: 35, color: '#60A5FA' },
  { name: 'B级', value: 28, color: '#34D399' },
  { name: 'C级', value: 20, color: '#FBBF24' },
  { name: 'D级', value: 17, color: '#F87171' }
]

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  const option = {
    color: creditLevels.map(item => item.color),
    series: [
      {
        type: 'pie',
        radius: ['60%', '85%'],
        center: ['50%', '50%'],
        data: creditLevels.map(item => ({
          name: item.name,
          value: item.value
        })),
        label: {
          show: false
        },
        emphasis: {
          scale: true,
          scaleSize: 10,
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'rgba(255, 255, 255, 0.1)',
      borderWidth: 1,
      padding: [8, 12],
      textStyle: {
        color: '#fff'
      }
    }
  }
  
  chart.setOption(option)
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => chart?.resize())
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', () => chart?.resize())
})
</script>
<template>
  <div class="chart-card">
    <div class="chart-header">企业信用等级分布</div>
    <div class="chart-content">
      <div class="chart-wrapper" ref="chartRef"></div>
      <div class="legend-wrapper">
        <div v-for="(item, index) in creditLevels" 
          :key="index"
          class="legend-item"
        >
          <div class="legend-color" :style="{ background: item.color }"></div>
          <div class="legend-label">{{ item.name }}</div>
          <div class="legend-value">{{ item.value }}%</div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.chart-card {
  background: rgba(30, 41, 59, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 20px;
  backdrop-filter: blur(8px);
  height: 100%;
}

.chart-header {
  color: #94A3B8;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
}

.chart-content {
  display: flex;
  height: calc(100% - 36px);
  gap: 24px;
}

.chart-wrapper {
  flex: 1;
  height: 100%;
  min-height: 200px;
}

.legend-wrapper {
  width: 120px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px 0;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-label {
  color: #94A3B8;
  font-size: 14px;
  flex: 1;
}

.legend-value {
  color: #E2E8F0;
  font-size: 14px;
  font-family: 'JetBrains Mono', monospace;
}
</style>
